#include "reg52.h"

sbit S4 = P3^3;
sbit S5 = P3^2;

unsigned char t_m = 0;
unsigned char t_s = 0;
unsigned char t_005s = 0;

unsigned char  code SMG[18] =	{0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};//0~9,A~F,还有小数点和一横


void selectHC573(unsigned char channel)
{
	switch(channel)
	{
		case 4:
			P2 = (P2 & 0x1f) | 0x80;
			break;
		case 5:
			P2 = (P2 & 0x1f) | 0xa0;
			break;
		case 6:
			P2 = (P2 & 0x1f) | 0xc0;
			break;	
		case 7:
			P2 = (P2 & 0x1f) | 0xe0;
			break;			
	}
}

void DisplaySMG_Bit(unsigned char digit,unsigned char pos)
{
	selectHC573(6);
	P0 = 0x01 <<	pos;
	selectHC573(7);
	P0 = digit;
}

void Delay(unsigned char t)
{
	while(t--);
}
	
void DisplaySMG_ALL()
{
		DisplaySMG_Bit(SMG[t_005s%10],7);
		Delay(500);
		DisplaySMG_Bit(SMG[t_005s/10],6);
		Delay(500);
		DisplaySMG_Bit(SMG[16],5);
		Delay(500);	
	
		DisplaySMG_Bit(SMG[t_s%10],4);
		Delay(500);
		DisplaySMG_Bit(SMG[t_s/10],3);
		Delay(500);
		DisplaySMG_Bit(SMG[16],2);
		Delay(500);	
	
		DisplaySMG_Bit(SMG[t_m%10],1);
		Delay(500);
		DisplaySMG_Bit(SMG[t_m/10],0);
		Delay(500);
}

void ScanKey()
{
	if(S5 == 0)
	{
		Delay(100);
		if(S5 == 0)	
		{
			t_m = 0;
			t_s = 0;
			t_005s = 0;
		}
	}
	if(S4 == 0)
	{
		Delay(100);
		if(S4 == 0)	
		{
			TR0 = ~TR0;
			while(S4 == 0)
			{
			DisplaySMG_ALL();
			}
		}
	}
	
}

void InitT0()
{
	TMOD = 0x01;
	TH0 = (65535 - 50000) / 256;
	TL0 = (65535 - 50000) % 256;
	
	EA = 1;
	TR0 = 1;
	ET0 = 1;
}

void ServeT0()		interrupt 1
{
	TH0 = (65535 - 50000) / 256;
	TL0 = (65535 - 50000) % 256;
	t_005s++;
	if(t_005s == 20)
	{
		t_s++;
		t_005s = 0;
	}
	
	if(t_s == 60)
	{
		t_m++;
		t_s = 0;
	}
}



void main()
{
	InitT0();
	
	while(1)
	{
		DisplaySMG_ALL();
		ScanKey();
	}
	
}